﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LiJu
{
    public partial class SystemManager : Form
    {


        public SystemManager()
        {
            InitializeComponent();


            // 加载时启用默认双缓冲并提供无闪烁的图形呈现：
            this.DoubleBuffered = true;//设置本窗体
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲

        }
        private void SystemManager_Load(object sender, EventArgs e)
        {


            SystemMenuIsFunction();

            LoadUserManagerInfo();
        }

        //调整选项卡文字方向
        private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
        {
            SolidBrush _Brush = new SolidBrush(Color.Black);//单色画刷
            RectangleF _TabTextArea = (RectangleF)tabControl1.GetTabRect(e.Index);//绘制区域
            StringFormat _sf = new StringFormat();//封装文本布局格式信息
            _sf.LineAlignment = StringAlignment.Center;
            _sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString(tabControl1.Controls[e.Index].Text, SystemInformation.MenuFont, _Brush, _TabTextArea, _sf);
        }


        #region 解决控件添加背景图后闪屏问题

        /// <summary>
        /// 防止闪屏
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                if (this.IsXpOr2003 == true)
                {
                    cp.ExStyle |= 0x00080000;
                    this.Opacity = 1;
                }
                return cp;
            }
        }

        private Boolean IsXpOr2003
        {
            get
            {
                OperatingSystem os = Environment.OSVersion;
                Version vs = os.Version;
                if (os.Platform == PlatformID.Win32NT)
                    if ((vs.Major == 5) && (vs.Major != 0))
                        return true;
                    else
                        return false;
                else
                    return false;

            }
        }

        #endregion

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.TabPages.Count > 0)
            {
                // 判断当前切换的tab,调用对应的加载方案
                switch (tabControl1.SelectedTab.Name)
                {
                    case "tabUser":
                        LoadUserManagerInfo();
                        break;
                    case "tabRole":
                        LoadRoleManagerInfo();
                        break;
                    case "tabMenu":
                        LoadSystemMenuInfo();
                        break;
                }
            }


        }

        #region 用户

        private void AddUserbutton_Click(object sender, EventArgs e)
        {
            AddUser addUser = new AddUser();
            //新增时ID为0
            AddUser.UId = 0;
            addUser.ShowDialog();
            LoadUserManagerInfo();
        }

        private void DgvUser_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 编辑功能
            if (DgvUser.Columns[e.ColumnIndex].Name == "BtnEditUser" && e.RowIndex >= 0)
            {


                AddUser.UId = Convert.ToInt32(DgvUser.Rows[e.RowIndex].Cells[1].Value);
                AddUser.UserId = Convert.ToString(DgvUser.Rows[e.RowIndex].Cells[2].Value);
                AddUser.UserName = Convert.ToString(DgvUser.Rows[e.RowIndex].Cells[3].Value);
                AddUser.PassWord = Convert.ToString(DgvUser.Rows[e.RowIndex].Cells[4].Value);
                AddUser.RoleId = Convert.ToInt32(DgvUser.Rows[e.RowIndex].Cells[5].Value);
                AddUser.RoleName = Convert.ToString(DgvUser.Rows[e.RowIndex].Cells[6].Value);
                AddUser.State = Convert.ToBoolean(DgvUser.Rows[e.RowIndex].Cells[7].Value);


                new AddUser().ShowDialog();
                LoadUserManagerInfo();


            }

            // 删除功能
            if (DgvUser.Columns[e.ColumnIndex].Name == "BtnDelUser" && e.RowIndex >= 0)
            {


                string userId = Convert.ToString(DgvUser.Rows[e.RowIndex].Cells[2].Value).ToLower();
                //不为管理员时可以删除
                if (userId != "admin" && userId != "administrator")
                {
                    if (MessageBox.Show("是否确认删除当前用户？", "删除操作！",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        //获取当前对象的ID
                        int uID = Convert.ToInt32(DgvUser.Rows[e.RowIndex].Cells[1].Value);


                        string sqls = string.Format(@"delete from usermanager where id={0}", uID);

                        var result = Db.DalMySQL.ExecuteNonQuery(sqls);
                        if (result > 0)
                        {

                            //删除当前行数据
                            DgvUser.Rows.RemoveAt(e.RowIndex);

                            MessageBox.Show("用户删除成功！", "操作提示!", MessageBoxButtons.OK, MessageBoxIcon.Question);
                            return;

                            //若后期一个用户对应多个角色 则需要清空用户角色分配表
                            //sqls = string.Format(@"delete from userinrole where id={0}", roleID);
                            //Db.DalMySQL.ExecuteNonQuery(sqls);

                        }
                    }



                }
            }
        }

        public void LoadUserManagerInfo()
        {

            DgvUser.Rows.Clear();

            string sql = "select a.Id,a.userID,a.userName,a.`password`,a.userRole,b.roleName,a.state from  usermanager a left join   rolemanager b on a.userRole = b.Id";

            var userList = UserOpMysql.ExecuteDataTable(sql);

            if (userList.Rows.Count > 0)
            {
                for (int i = 0; i < userList.Rows.Count; i++)
                {
                    DgvUser.Rows.Add();

                    DgvUser.Rows[i].Cells[0].Value = i + 1;
                    DgvUser.Rows[i].Cells[1].Value = userList.Rows[i]["Id"];
                    DgvUser.Rows[i].Cells[2].Value = userList.Rows[i]["userID"];
                    DgvUser.Rows[i].Cells[3].Value = userList.Rows[i]["userName"];
                    DgvUser.Rows[i].Cells[4].Value = userList.Rows[i]["password"];
                    DgvUser.Rows[i].Cells[5].Value = userList.Rows[i]["userRole"];
                    DgvUser.Rows[i].Cells[6].Value = userList.Rows[i]["roleName"];
                    DgvUser.Rows[i].Cells[7].Value = userList.Rows[i]["state"];

                }
            }
        }

        #endregion

        #region 角色
        private void BtnAddRole_Click(object sender, EventArgs e)
        {
            AddRole addRole = new AddRole();
            //新增时ID为0
            AddRole.RoleId = 0;
            addRole.ShowDialog();
            LoadRoleManagerInfo();
        }



        private void DgvRole_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 编辑功能
            if (DgvRole.Columns[e.ColumnIndex].Name == "BtnEditRole" && e.RowIndex >= 0)
            {

                AddRole.RoleId = Convert.ToInt32(DgvRole.Rows[e.RowIndex].Cells[1].Value);
                AddRole.RoleName = Convert.ToString(DgvRole.Rows[e.RowIndex].Cells[2].Value);
                AddRole.RoleState = Convert.ToBoolean(DgvRole.Rows[e.RowIndex].Cells[5].Value);


                new AddRole().ShowDialog();
                LoadRoleManagerInfo();


            }

            // 删除功能
            if (DgvRole.Columns[e.ColumnIndex].Name == "BtnDelRole" && e.RowIndex >= 0)
            {
                if (MessageBox.Show("是否确认删除当前角色？", "删除操作！",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //获取当前对象的ID
                    int roleID = Convert.ToInt32(DgvRole.Rows[e.RowIndex].Cells[1].Value);


                    string sqls = string.Format(@"delete from rolemanager where id={0}", roleID);

                    var result = Db.DalMySQL.ExecuteNonQuery(sqls);
                    if (result > 0)
                    {
                        //清除角色菜单表记录
                        sqls = string.Format(@"delete from roleinmenu where roleID={0}", roleID);
                        Db.DalMySQL.ExecuteNonQuery(sqls);

                        //删除当前行数据
                        DgvRole.Rows.RemoveAt(e.RowIndex);

                        MessageBox.Show("角色删除成功！", "操作提示!", MessageBoxButtons.OK, MessageBoxIcon.Question);
                        return;


                    }




                    //string sqls = string.Format(@"select * from roleinmenu where roleID={0}", roleID);
                    //bool isPar = Db.DalMySQL.Exists(sqls);
                    //if (isPar)
                    //{
                    //    MessageBox.Show("当前角色存在子菜单，请先删除其子菜单！", "操作异常！", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    //}
                    //else
                    //{
                    //    string sql = string.Format(@"delete from systemmenu where id={0}", roleID);

                    //    var resust = Db.DalMySQL.ExecuteNonQuery(sql);
                    //    if (resust > 0)
                    //    {
                    //        //删除当前行数据
                    //        DgvRole.Rows.RemoveAt(e.RowIndex);
                    //    }
                    //}



                }
            }
        }

        public void LoadRoleManagerInfo()
        {

            DgvRole.Rows.Clear();

            string sql = "SELECT a.*,(SELECT COUNT(*) FROM usermanager where userRole= a.Id) as 'EmployCount' FROM rolemanager a";

            var menuList = UserOpMysql.ExecuteDataTable(sql);

            if (menuList.Rows.Count > 0)
            {
                for (int i = 0; i < menuList.Rows.Count; i++)
                {
                    DgvRole.Rows.Add();

                    DgvRole.Rows[i].Cells[0].Value = i + 1;
                    DgvRole.Rows[i].Cells[1].Value = menuList.Rows[i]["id"];
                    DgvRole.Rows[i].Cells[2].Value = menuList.Rows[i]["RoleName"];
                    DgvRole.Rows[i].Cells[3].Value = menuList.Rows[i]["RolePermissions"];
                    DgvRole.Rows[i].Cells[4].Value = menuList.Rows[i]["EmployCount"];
                    DgvRole.Rows[i].Cells[5].Value = menuList.Rows[i]["State"];
                    DgvRole.Rows[i].Cells[5].Value = menuList.Rows[i]["State"];

                }
            }
        }
        #endregion

        #region 菜单

        private void BtnMenu_Click(object sender, EventArgs e)
        {
            AddMenu addMenu = new AddMenu();
            AddMenu.Id = 0;
            addMenu.ShowDialog();

            //添加功能关闭后刷新数据
            LoadSystemMenuInfo();
        }


        public void LoadSystemMenuInfo()
        {

            DgvMenu.Rows.Clear();

            string sql = "SELECT * FROM systemmenu";

            var menuList = UserOpMysql.ExecuteDataTable(sql);

            if (menuList.Rows.Count > 0)
            {
                for (int i = 0; i < menuList.Rows.Count; i++)
                {
                    DgvMenu.Rows.Add();

                    DgvMenu.Rows[i].Cells[0].Value = i + 1;
                    DgvMenu.Rows[i].Cells[1].Value = menuList.Rows[i]["MenuNo"];
                    DgvMenu.Rows[i].Cells[2].Value = menuList.Rows[i]["MenuName"];
                    DgvMenu.Rows[i].Cells[3].Value = menuList.Rows[i]["MenuType"];
                    DgvMenu.Rows[i].Cells[4].Value = menuList.Rows[i]["ParentName"];
                    DgvMenu.Rows[i].Cells[5].Value = menuList.Rows[i]["MenuState"];
                    DgvMenu.Rows[i].Cells[6].Value = menuList.Rows[i]["CreateTime"];
                    DgvMenu.Rows[i].Cells[7].Value = menuList.Rows[i]["CreateUser"];
                    DgvMenu.Rows[i].Cells[8].Value = menuList.Rows[i]["id"];

                }
            }
        }

        private void DgvMenu_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 编辑功能
            if (DgvMenu.Columns[e.ColumnIndex].Name == "BtnEditMenu" && e.RowIndex >= 0)
            {

                AddMenu.Id = Convert.ToInt32(DgvMenu.Rows[e.RowIndex].Cells[8].Value);
                AddMenu.MenuNo = Convert.ToString(DgvMenu.Rows[e.RowIndex].Cells[1].Value);
                AddMenu.MenuName = Convert.ToString(DgvMenu.Rows[e.RowIndex].Cells[2].Value);
                AddMenu.MenuType = Convert.ToString(DgvMenu.Rows[e.RowIndex].Cells[3].Value);
                AddMenu.ParentName = Convert.ToString(DgvMenu.Rows[e.RowIndex].Cells[4].Value);
                AddMenu.MenuState = Convert.ToInt32(DgvMenu.Rows[e.RowIndex].Cells[5].Value);

                new AddMenu().ShowDialog();

                //添加功能关闭后刷新数据
                LoadSystemMenuInfo();

            }

            // 删除功能
            if (DgvMenu.Columns[e.ColumnIndex].Name == "BtnDelMenu" && e.RowIndex >= 0)
            {
                //获取当前对象的ID
                int menuId = Convert.ToInt32(DgvMenu.Rows[e.RowIndex].Cells[8].Value);
                if (menuId != 1)
                {
                    if (MessageBox.Show("是否确认删除当前菜单？", "删除操作！",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {


                        string sqls = string.Format(@"select * from systemmenu where Parentid={0}", menuId);
                        bool isPar = Db.DalMySQL.Exists(sqls);
                        if (isPar)
                        {
                            MessageBox.Show("当前菜单存在子菜单，请先删除其子菜单！", "操作异常！", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                            return;
                        }
                        else
                        {
                            string sql = string.Format(@"delete from systemmenu where id={0}", menuId);

                            var result = Db.DalMySQL.ExecuteNonQuery(sql);
                            if (result > 0)
                            {
                                //删除当前行数据
                                DgvMenu.Rows.RemoveAt(e.RowIndex);

                                MessageBox.Show("菜单删除成功！", "操作提示!", MessageBoxButtons.OK, MessageBoxIcon.Question);
                                return;
                            }
                        }

                    }





                }
            }
        }

        #endregion

        /// <summary>
        /// 页面功能加载
        /// </summary>
        public void SystemMenuIsFunction()
        {


            string userID = ConfigurationManager.AppSettings["UserID"];

            tabControl1.TabPages.Clear();

            AddUserbutton.Enabled = false;
            BtnAddRole.Enabled = false;

            BtnDelUser.Visible = false;
            BtnDelRole.Visible = false;


            BtnEditUser.Visible = false;
            BtnEditRole.Visible = false;

            //页面元素
            //获取当前页面功能
            var menuRole = PageDataDto.SystemMenuRoleInfo();

            if (menuRole.UserManager || userID == "admin")
            {
                tabControl1.TabPages.Add(tabUser);
            }
            if (menuRole.RoleManager || userID == "admin")
            {
                tabControl1.TabPages.Add(tabRole);
            }
            if (menuRole.Systemlog || userID == "admin")
            {
                tabControl1.TabPages.Add(tabSystemLog);
            }
            if (menuRole.User_Add || userID == "admin")
            {
                AddUserbutton.Enabled = true;
            }
            if (menuRole.User_Edit || userID == "admin")
            {
                BtnEditUser.Visible = true;
            }
            if (menuRole.User_Del || userID == "admin")
            {
                BtnDelUser.Visible = true;
            }
            if (menuRole.Role_Add || userID == "admin")
            {
                BtnAddRole.Enabled = true;
            }
            if (menuRole.Role_Edit || userID == "admin")
            {
                BtnEditRole.Visible = true;
            }
            if (menuRole.Role_Del || userID == "admin")
            {
                BtnDelRole.Visible = true;
            }



        }
    }
}
